import { LibAppView } from "@/lib";
import { App, Button, Card, Form, Input, Select, Switch, Radio } from "antd";
import React, { useCallback, useMemo, useState } from "react";
import { FormattedMessage, useIntl } from "react-intl";

import styles from "./styles.module.scss";
import Upload from "../../Component/ResourceList/Upload";
import RegionPicker from "../../Component/RegionPicker";
import SourceEdit from "./SourceEdit";
import RichText from "../../Component/ResourceList/RichText";
import { AdminRight, useAdminRight } from "@/pages/Admin/data/AdminPageAuth";
import { Cover } from "@/pages/Admin/Component/Cover";


interface IOption {
    label: string;
    value: string;
}

const getOptionLabel = (optionList: IOption[], value: string) => {
    return optionList.find(item => item.value === value)?.label || "";
};


const EditArticle = LibAppView.withService({
    reqEndPoints: [{
        endPoint: "article.config",
        name: "config"
    }]
})((props) => {
    const app = LibAppView.useApp();
    const microApp = LibAppView.useMicroApp();
    const antApp = App.useApp();
    const intl = useIntl();
    const journeyData = LibAppView.useJourneyData();
    const editData = journeyData.currentStepState || {};
    const hasEditRight = useAdminRight("editable");
    const [ form ] = Form.useForm();
    const [ componentDisabled, setComponentDisabled] = useState(!hasEditRight);
    
    const [ categoryName, setCategoryName] = useState(() => {
        return editData?.categoryName;
    });
    const categoryList = useMemo(() => {
        const categoryData = (props.responseData as any).config?.data?.category || [];
        return categoryData;
    }, [props.responseData]);
    const typeList = useMemo(() => {
        return (props.responseData as any).config?.data?.actType || [];
    }, [props.responseData]);
    const audienceList = useMemo(() => {
        return (props.responseData as any).config?.data?.audience || [];
    }, [props.responseData]);
    const [ defaultFormData, setDefaultFormData ] = useState({
        ...editData,
        status: editData.status === 1,
        isRef: editData.isRef ? editData.isRef : 0,
        region: editData.region?.length > 0 ? JSON.parse(editData.region) : []
    });
    const [ artType, setArtType ] = useState(defaultFormData.artType);

    const onSubmit = useCallback(() => {
        const formData = form.getFieldsValue();
        form.validateFields().then(() => {
            formData.status = formData.status ? 1 : 0;
            setComponentDisabled(true);console.log(formData);
            app.serviceApi.send({
                endPoint: "article.submit",
                data: {
                    ...formData,
                    categoryTitle: getOptionLabel(categoryList, formData.categoryName),
                    artTitle: getOptionLabel(typeList, formData.artType),
                    targetAudienceTitle: getOptionLabel(audienceList, formData.targetAudience),
                    id: defaultFormData.id,
                    isHot: formData.isHot ? 1 : 0,
                    popularScience: formData.popularScience ? 1 : 0,
                    region: formData.categoryName === "PSB" ? JSON.stringify(formData.region) : "",
                    status: 1
                }
            }).then(() => {
                setComponentDisabled(false);
                antApp.message.success(
                    intl.formatMessage({ id: "admin.pages.form.submit.success", defaultMessage: "Submit successfully."}), 3);
                    microApp.goBack();
            }).catch((err) => {
                setComponentDisabled(false);
                antApp.message.error(err.message);
            });
        }).catch((err) => {
            antApp.message.error(err.message || intl.formatMessage({ id: "admin.pages.article.formItem.required", defaultMessage: "Please enter the article title."}));
        });
    }, [form, defaultFormData, categoryList, typeList, audienceList]);
    const formRule = useMemo(() => {
        return [{ required: true, message: intl.formatMessage({ id: "admin.pages.article.formItem.required", defaultMessage: "Please enter the article title."}) }];
    }, []);

    const onValuesChange = (frmData: any) => {
        if(frmData.artType && frmData.artType !== artType) {
            const formDataSubmitData: any = {
                ...form.getFieldsValue()
            };
            delete formDataSubmitData.id;
            setArtType(frmData.artType);
            form.setFieldValue("source", []);
            setDefaultFormData({
                ...formDataSubmitData,
                id: defaultFormData.id,
                source: "[]"
            });
        }
        if(frmData.categoryName && frmData.categoryName !== categoryName) {
            setCategoryName(frmData.categoryName);
        }
    };
    return (
        <Card style={{ width: "100%", minHeight: "76vh", padding: 20 }}>
        <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 12 }}
            layout="horizontal"
            disabled={componentDisabled}
            form={form}
            initialValues={defaultFormData}
            onValuesChange={onValuesChange}
        >
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.title" />}
                name="title"
                rules={formRule}
                required
            >
                <Input type="text" autoComplete="off"/>
            </Form.Item>
            <Form.Item
                label="是否头条"
                name="isHot"
            >
                <Switch />
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.header" />}
                name="header"
                required
                rules={formRule}
            >
                <Cover filterType="image" />
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.desc" />}
                name="description"
            >
                <Input.TextArea autoSize={{ minRows: 4, maxRows: 8 }} />
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.keywords" />}
                name="keywords"
                required
                rules={formRule}
            >
                <Input type="text" />
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.isOriginal" />}
                name="isOriginal"
                rules={formRule}
                required
            >
                <Radio.Group>
                    <Radio value={0}><FormattedMessage id="admin.pages.article.original.false" /></Radio>
                    <Radio value={1}><FormattedMessage id="admin.pages.article.original.true" /></Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.category" />}
                name="categoryName"
                rules={formRule}
                required
            >
                <Select options={categoryList} />
            </Form.Item>
            { categoryName === "PSB" && <Form.Item
                label="基地位置"
                name="region"
                rules={formRule}
                required
            >
                <RegionPicker />
            </Form.Item> }
            <Form.Item
                label={"受众群体"}
                name="targetAudience"
            >
                <Select options={audienceList}  />
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.typeTile" />}
                name="artType"
                rules={formRule}
                required
            >
                <Select options={typeList}  />
            </Form.Item>
            { artType !== 'txtimg' && <Form.Item
                label="文件资源"
                name="source"
            >
                <SourceEdit sourceData={defaultFormData.sourceData} artType={artType}/>
            </Form.Item> }
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.content" />}
                name="content"
                rootClassName={styles.articalEditorFormItem}
            >
                <RichText />
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.menus.edit.isRef" />}
                name="isRef"
            >
                <Radio.Group>
                    <Radio value={0}>否</Radio>
                    <Radio value={1}>是</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                label={<FormattedMessage id="admin.pages.article.refUrl" />}
                name="refUrl"
            >
                <Input type="text" />
            </Form.Item>
            <Form.Item
                label={"是否科普月专栏资源"}
                name="popularScience"
            >
               <Switch />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
                <AdminRight authRight="editable" mode="disabled">
                    <Button loading={componentDisabled} type="primary" htmlType="submit" onClick={onSubmit}>
                        <FormattedMessage id="admin.pages.form.submit" />
                    </Button>
                </AdminRight>
                <Button style={{marginLeft: 10}} type="default" onClick={() => {
                    microApp.goBack();
                }}>
                    <FormattedMessage id="admin.pages.form.back" />
                </Button>
            </Form.Item>
        </Form>
    </Card>
    );
});

export default EditArticle;
